package com.csi.jf.crucible.api.sonar;

import org.sonar.wsclient.internal.HttpRequestFactory;
import org.sonar.wsclient.permissions.PermissionParameters;
import org.sonar.wsclient.permissions.internal.DefaultPermissionClient;
import org.sonar.wsclient.project.NewProject;
import org.sonar.wsclient.project.internal.DefaultProjectClient;
import org.sonar.wsclient.user.User;
import org.sonar.wsclient.user.UserParameters;
import org.sonar.wsclient.user.UserQuery;
import org.sonar.wsclient.user.internal.DefaultUserClient;

public class SonarApiUtil {

    /********************* 静态参数 *******************************/
    public static String SONAR_URL = "http://115.29.76.124:9000";

    private static String adminLogin = "admin";

    private static String adminPassword = "123456";

    private static HttpRequestFactory requestFactory = null;

    /********************* 静态参数end *******************************/
    /********************* 静态方法 *******************************/

    /**
     * 初始化构造
     */
    public SonarApiUtil(String url, String login, String password) {
        SonarApiUtil.SONAR_URL = url;
        SonarApiUtil.adminLogin = login;
        SonarApiUtil.adminPassword = password;

        if (requestFactory == null) {
            requestFactory = new HttpRequestFactory(url);
            requestFactory.setLogin(adminLogin);
            requestFactory.setPassword(adminPassword);
        }
    }

    /**
     * 初始化构造
     */
    public SonarApiUtil() {
        if (requestFactory == null) {
            requestFactory = new HttpRequestFactory(SONAR_URL);
            requestFactory.setLogin(adminLogin);
            requestFactory.setPassword(adminPassword);
        }
    }

    /**
     * 授予用户权限
     * 
     * @param permission
     *            权限标示，一般只给scan,shareDashboard,user,codeviewer,issueadmin权限,
     *            传入多个权限时之间用，隔开 
     *            
     *            全局权限： admin Administer System 
     *            系统管理员 dryRunScan
     *            Execute Preview Analysis 执行本地分析（干跑） profileadmin Administer
     *            Quality Profiles 
     *            质量配置管理员 provisioning Provision Projects 
     *            配置项目
     *            scan Execute Analysis 执行分析 shareDashboard Share Dashboards and
     *            Filters 共享仪表盘和过滤器 
     *            
     *            项目权限： 
     *            user Browse 角色：用户 admin Administer 角色：管理员 
     *            codeviewer See Source Code 角色：代码复查 issueadmin
     *            Administer Issues 问题管理员
     * @param login
     *            用户登陆名，对应SONAR的login
     * @param projectKey
     *            项目标示，对应SONAR的项目关键字（Key）
     */
    public int insertUserPermission(String permissions, String login,
            String projectKey) {
        if (login == null || login.equals(""))
            return SonarConstant.LoginIsNull;

        DefaultPermissionClient dClient = new DefaultPermissionClient(
                requestFactory);

        PermissionParameters newPermission = PermissionParameters.create();

        newPermission.user(login);
        if (projectKey != null){
            newPermission.component(projectKey);
        }
        String permissionList[] = permissions.split(",");
        for (int i = 0; i < permissionList.length; i++) {
            newPermission.permission(permissionList[i]);
            dClient.addPermission(newPermission);
        }

        return SonarConstant.Success;
    }

    /**
     * 移除用户权限
     * 
     * @param permission
     *            权限标示，一般只移除scan,shareDashboard,user,codeviewer,issueadmin权限,
     *            传入多个权限时之间用，隔开 全局权限： admin Administer System 系统管理员 dryRunScan
     *            Execute Preview Analysis 执行本地分析（干跑） profileadmin Administer
     *            Quality Profiles 质量配置管理员 provisioning Provision Projects 配置项目
     *            scan Execute Analysis 执行分析 shareDashboard Share Dashboards and
     *            Filters 共享仪表盘和过滤器 项目权限： user Browse 角色：用户 admin Administer
     *            角色：管理员 codeviewer See Source Code 角色：代码复查 issueadmin
     *            Administer Issues 问题管理员
     * @param login
     *            用户登陆名，对应SONAR的login
     * @param projectKey
     *            项目标示，对应SONAR的项目关键字（Key）。配置全局权限时传入null。
     */
    public int removeUserPermission(String permissions, String login,
            String projectKey) {
        if (login == null || login.equals(""))
            return SonarConstant.LoginIsNull;

        DefaultPermissionClient dClient = new DefaultPermissionClient(
                requestFactory);

        PermissionParameters newPermission = PermissionParameters.create();

        newPermission.user(login);
        if (projectKey != null)
            newPermission.component(projectKey);

        String permissionList[] = permissions.split(",");
        for (int i = 0; i < permissionList.length; i++) {
            newPermission.permission(permissionList[i]);
            dClient.removePermission(newPermission);
        }

        return SonarConstant.Success;
    }

    /**
     * 插入用户
     * 
     * @param login
     *            登陆名，对应SONAR的login
     * @param password
     *            密码,不能为1，否则报错
     * @param name
     *            用户姓名，对应SONAR的name
     */
    public int insertUser(String login, String password, String name) {
        if (login == null || login.equals(""))
            return SonarConstant.LoginIsNull;
        else if (password == null || password.equals(""))
            return SonarConstant.PasswordIsNull;
        else if (password.equals("1"))
            return SonarConstant.PasswordIsOne;
        else if (name == null || name.equals(""))
            return SonarConstant.NameIsNull;

        DefaultUserClient uClient = new DefaultUserClient(requestFactory);
        UserQuery uq = UserQuery.create();

        boolean isFind = false;
        for (User us : uClient.find(uq)) {
            if (us.login().equals(login)) {
                isFind = true;
                break;
            }
        }

        if (!isFind) {
            UserParameters newUser = UserParameters.create();
            newUser.login(login);
            newUser.password(password);
            newUser.passwordConfirmation(password);
            newUser.name(name);
            newUser.email(login);

            uClient.create(newUser);
        }

        return SonarConstant.Success;
    }

    /**
     * 更新用户
     * 
     * @param login
     *            登陆名，对应SONAR的login
     * @param password
     *            密码,不更新则传null
     * @param name
     *            用户姓名，不更新则传null
     */
    public int updateUser(String login, String password, String name) {
        if (login == null || login.equals(""))
            return SonarConstant.LoginIsNull;

        DefaultUserClient uClient = new DefaultUserClient(requestFactory);
        UserQuery uq = UserQuery.create();

        boolean isFind = false;
        for (User us : uClient.find(uq)) {
            if (us.login().equals(login)) {
                isFind = true;
                break;
            }
        }

        if (isFind) {
            UserParameters user = UserParameters.create();
            user.login(login);
            if (password != null) {
                user.password(password);
                user.passwordConfirmation(password);
            }

            if (name != null)
                user.name(name);

            user.email(login);
            uClient.update(user);
        }

        return SonarConstant.Success;
    }

    /**
     * 删除用户
     * 
     * @param login
     *            登录名，对应SONAR的login
     */
    public int deleteUser(String login) {
        if (login == null || login.equals(""))
            return SonarConstant.LoginIsNull;

        DefaultUserClient uClient = new DefaultUserClient(requestFactory);

        uClient.deactivate(login);
        return SonarConstant.Success;
    }

    /**
     * 创建项目
     * 
     * @param newProject
     *            NewProject newProject = NewProject.create();
     *            newProject.key("pst_test_key");
     *            newProject.name("pts_test_name");
     */
    public void createProject(NewProject newProject) {
        // HttpRequestFactory requestFactory
        DefaultProjectClient dpc = new DefaultProjectClient(requestFactory);
        dpc.create(newProject);
    }

    /********************* 静态方法end *******************************/
}
